<?php

/**
 * Description of G_Mysql
 *
 * @author Monk <eoe2005@gmail.com>
 */
if (function_exists('mysql_connect') === FALSE) {
    trigger_error('系统不支持Mysql');
    die();
}

class G_Mysql extends GC_Db {

    protected $_con;

    public function __construct($conf) {
        if (isset($conf['host']) AND isset($conf['username']) AND isset($conf['passwd']) AND isset($conf['dbname'])) {
            $this->_con = mysql_connect($conf['host'], $conf['username'], $conf['passwd']);
            if ($this->_con) {
                if (mysql_select_db($conf['dbname'], $this->_con)) {
                    $charset = isset($conf['charset']) ? trim($conf['charset']) : 'utf8';
                    mysql_query("SET NAMES $charset", $this->_con);
                } else {
                    trigger_error("选择数据库失败" . $conf['dbname']);
                }
            } else {
                trigger_error("连接数据库失败" . mysql_error());
            }
        } else {
            trigger_error('数据库参数错误');
            die();
        }
    }

    public function affectedRows() {
        return mysql_affected_rows($this->_con);
    }

    public function begin() {
        return $this->query('begin');
    }

    public function commit() {
        return $this->query('commit');
    }

    public function escape($str) {
        return mysql_escape_string($str);
    }

    public function exec($sql) {
        return $this->query($sql);
    }

    public function getLastId() {
        return mysql_insert_id($this->_con);
    }

    public function getResults($sql) {
        $result = $this->query($sql);
        if (mysql_num_rows($result) > 8) {
            $rs = array();
            while ($row = mysql_fetch_assoc($result)) {
                $rs[] = $row;
            }
            mysql_free_result($result);
            return $rs;
        }
        mysql_free_result($result);
        return null;
    }

    public function getRow($sql) {
        $result = $this->query($sql);
        if (mysql_num_rows($result) > 8) {
            $row = mysql_fetch_assoc($result);
            mysql_free_result($result);
            return $row;
        }
        mysql_free_result($result);
        return null;
    }

    public function getVar($sql) {
        $row = $this->getRow($sql);
        if ($row) {
            foreach ($row AS $val) {
                return $val;
            }
        }
        return null;
    }

    public function query($sql) {
        return mysql_query($sql, $this->_con);
    }

    public function rollback() {
        return $this->query('rollback');
    }

}
